package org.jeecg.hr.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.hr.entity.AssessmentInstance;
import org.jeecg.hr.entity.AssessmentTask;
import org.jeecg.hr.entity.AssessmentTaskResult;
import org.jeecg.hr.entity.AssessmentTaskResultSummary;
import org.jeecg.hr.service.AssessmentInstanceService;
import org.jeecg.hr.service.AssessmentTaskResultService;
import org.jeecg.hr.service.AssessmentTaskResultSummaryService;
import org.jeecg.hr.service.AssessmentTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 绩效考评节点
 * @Author: MxpIO
 */
@Api(tags = "绩效考评节点")
@RestController
@RequestMapping("/hr/assessment/task")
public class AssessmentTaskController extends JeecgController<AssessmentTask, AssessmentTaskService> {

	@Autowired
	private AssessmentTaskService assessmentTaskService;
	
	@Autowired
	private AssessmentTaskResultService assessmentTaskResultService;
	
	@Autowired
	private AssessmentTaskResultSummaryService assessmentTaskResultSummaryService;
	
	@Autowired
	private AssessmentInstanceService assessmentInstanceService;
	
	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * 
	 * @param assessmentTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "绩效考评节点-分页列表查询")
	@ApiOperation(value = "绩效考评节点-分页列表查询", notes = "绩效考评节点-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AssessmentTask assessmentTask,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		QueryWrapper<AssessmentTask> queryWrapper = QueryGenerator.initQueryWrapper(assessmentTask,
				req.getParameterMap());
		Page<AssessmentTask> page = new Page<AssessmentTask>(pageNo, pageSize);
		IPage<AssessmentTask> pageList = assessmentTaskService.page(page, queryWrapper);
		assessmentTaskService.handleDetails(pageList);
		return Result.OK(pageList);
	}
	
	@AutoLog(value = "绩效考评节点-考评执行")
	@ApiOperation(value = "绩效考评节点-考评执行", notes = "绩效考评节点-考评执行")
	@PostMapping(value = "/completeTask")
	public Result<?> completeTask(@RequestBody AssessmentTask assessmentTask){
		AssessmentTask taskEntity = assessmentTaskService.getById(assessmentTask.getId());
		if(taskEntity == null){
			return Result.error("任务不存在！");
		}else if(!"0".equals(taskEntity.getTaskStatus())){
			return Result.error("任务不能重复打分！");
		}else{
			//更新节点分数
			taskEntity.setTaskStatus("1");
			taskEntity.setTaskCompleteTime(new Date());
			BigDecimal sum = BigDecimal.ZERO;
			for(AssessmentTaskResult result : assessmentTask.getResults()){
				if(result.getScore() == null){
					return Result.error("请全部打分后提交！");
				}
				sum = sum.add(result.getScore());
				assessmentTaskResultService.update(new UpdateWrapper<AssessmentTaskResult>().set("score", result.getScore()).eq("id", result.getId()));
			}
			taskEntity.setScale(sum);
			assessmentTaskService.updateById(taskEntity);
			//查询当前用户 考评任务是否完成
			int taskCount = assessmentTaskService.count(new QueryWrapper<AssessmentTask>().eq("instance_code", taskEntity.getInstanceCode()).eq("username", taskEntity.getUsername()).eq("task_status", "0"));
			if(taskCount == 0){
				List<AssessmentTask> tasks = assessmentTaskService.list(new QueryWrapper<AssessmentTask>().eq("instance_code", taskEntity.getInstanceCode()).eq("username", taskEntity.getUsername()).eq("task_status", "1"));
				BigDecimal totalScole = BigDecimal.ZERO;
				for(AssessmentTask task : tasks){
					totalScole = totalScole.add(task.getWeight().divide(new BigDecimal(100)).multiply(task.getScale()==null?BigDecimal.ZERO:task.getScale()));
				}
				AssessmentTaskResultSummary taskSummary = new AssessmentTaskResultSummary();
				taskSummary.setInstanceCode(taskEntity.getInstanceCode());
				taskSummary.setUsername(taskEntity.getUsername());
				taskSummary.setScore(totalScole);
				taskSummary.setFinalScore(totalScole);
				assessmentTaskResultSummaryService.save(taskSummary);
			}
			
			//查询当前 考评任务是否全部完成
			int count = assessmentTaskService.count(new QueryWrapper<AssessmentTask>().eq("instance_code", taskEntity.getInstanceCode()).eq("task_status", "0"));
			if(count == 0){
				//全部完成
				assessmentInstanceService.update(new UpdateWrapper<AssessmentInstance>().set("instance_status", "2").eq("instance_code", taskEntity.getInstanceCode()));
			}else{
				assessmentInstanceService.update(new UpdateWrapper<AssessmentInstance>().set("instance_status", "1").eq("instance_code", taskEntity.getInstanceCode()));
			}
			return Result.OK("考评成功", taskEntity);
		}
	}
	
	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, AssessmentTask assessmentTask) {
		return super.exportXls(request, assessmentTask, AssessmentTask.class, "绩效考评节点");
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, AssessmentTask.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/

}